<template>
  <el-card header="扫码登录B站账号" class="soft-card">
    <div class="soft-qrcode-wrap">
      <img v-if="imgUrl" :src="imgUrl" class="soft-qrcode" />
    </div>
    <div v-if="qrcodeUrl" class="soft-link">扫码链接：<el-link :href="qrcodeUrl" target="_blank">{{ qrcodeUrl }}</el-link></div>
    <div style="margin: 10px 0 8px 0; display: flex; align-items: center; justify-content: center; gap: 12px;">
      <el-switch v-model="isAlt" active-text="写入小号" inactive-text="写入主号" />
      <span style="color:#b48ad6; font-size:0.98rem;">（开关决定扫码写入主号还是小号cookie）</span>
    </div>
    <el-button @click="refresh" class="soft-btn">刷新二维码</el-button>
    <div class="soft-tip">请使用B站App扫码登录，登录后cookie会自动保存~</div>
  </el-card>
</template>
<script setup>

import { ElMessage } from 'element-plus'
import { getQrcode } from '../api'
import { ref, onMounted, onUnmounted } from 'vue'
import axios from 'axios'
import { checkBiliCookie } from '../bili_utils'
let timer = null
let polling = false
const imgUrl = ref(''), qrcodeUrl = ref(''), qrcodeKey = ref(''), loggedIn = ref(false)
const isAlt = ref(false)

const refresh = async () => {
  const res = await getQrcode()
  imgUrl.value = URL.createObjectURL(res.data)
  qrcodeUrl.value = res.headers['x-qrcode-url']
  qrcodeKey.value = res.headers['x-qrcode-key']
  ElMessage.info('请使用B站App扫码登录~ฅ^•ﻌ•^ฅ')
  loggedIn.value = false
  stopPolling()
  setTimeout(() => {
    if (!loggedIn.value) startPolling()
  }, 1500)
}


const checkQrcodeStatus = async () => {
  if (!qrcodeKey.value) return
  try {
    const res = await axios.get(`/api/bili/qrcode_status?qrcode_key=${qrcodeKey.value}&is_alt=${isAlt.value}`)
    const data = res.data && res.data.data ? res.data.data : null
    // 1. 扫码成功且cookie有效，后端返回cookie_valid为true才弹窗
    if (data && data.cookie_valid) {
      if (!loggedIn.value) {
        loggedIn.value = true
        stopPolling()
        import('element-plus').then(({ ElMessage }) => {
          ElMessage.success('登录成功，cookie已写入，可正常使用！')
        })
      }
      return
    }
    // 2. 扫码成功但cookie无效，提示用户cookie无效
    if (data && data.url && data.cookie_valid === false) {
      stopPolling()
      import('element-plus').then(({ ElMessageBox }) => {
        ElMessageBox.confirm(
          '扫码成功但cookie无效，请重试或更换网络/账号',
          '提示',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }
        ).then(() => {
          refresh()
        }).catch(() => {
          // 取消不处理
        })
      })
      return
    }
    // 3. 二维码失效
    if (
      data && (
        data.code === 412 ||
        (data.msg && data.msg.includes('失效')) ||
        data.code === 86038 ||
        (data.message && data.message.includes('失效'))
      )
    ) {
      stopPolling()
      import('element-plus').then(({ ElMessageBox }) => {
        ElMessageBox.confirm(
          '二维码已失效，是否立即刷新？',
          '提示',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }
        ).then(() => {
          refresh()
        }).catch(() => {
          // 取消不处理
        })
      })
      return
    }
  } catch (e) {
    // 网络异常等其它错误
  }
}

function startPolling() {
  if (polling) return
  polling = true
  pollLoop()
}

function stopPolling() {
  polling = false
  if (timer) {
    clearTimeout(timer)
    timer = null
  }
}

function pollLoop() {
  if (!polling) return
  checkQrcodeStatus().finally(() => {
    if (polling && !loggedIn.value) {
      timer = setTimeout(pollLoop, 2500)
    }
  })
}


const checkLoginAndCookie = async () => {
  // 检查cookie有效性，若有效则弹窗提示登录成功
  console.log('[扫码] 检测cookie有效性...')
  const cookieValid = await checkBiliCookie()
  console.log('[扫码] 首次检测cookie结果:', cookieValid)
  if (cookieValid) {
    loggedIn.value = true
    clearTimeout(timer)
    import('element-plus').then(({ ElMessage }) => {
      ElMessage.success('登录成功，cookie已写入，可正常使用！')
    })
    // 登录成功后立即再次检测cookie有效性
    setTimeout(async () => {
      const valid = await checkBiliCookie()
      console.log('[扫码] 二次检测cookie结果:', valid)
      if (!valid) {
        import('element-plus').then(({ ElMessageBox }) => {
          ElMessageBox.confirm(
            '写入的cookie不可用，请重新扫码登录！',
            '提示',
            {
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              type: 'warning',
            }
          ).then(() => {
            refresh()
          }).catch(() => {
            // 取消不处理
          })
        })
      }
    }, 500)
    return
  }
  // 若cookie无效，检测二维码
  checkQrcodeStatus()
}

onMounted(() => {
  refresh()
  window.addEventListener('bili-login-success', checkLoginAndCookie)
})
onUnmounted(() => {
  stopPolling()
  window.removeEventListener('bili-login-success', checkLoginAndCookie)
})
</script>
<style scoped>
.soft-card {
  border-radius: 0;
  box-shadow: none;
  margin: 0;
  background: #fff6fa;
  border: none;
  text-align: center;
  width: 100%;
  padding: 0;
}
.soft-qrcode-wrap {
  display: flex;
  justify-content: center;
  margin: 18px 0 8px 0;
}
.soft-qrcode {
  width: 180px;
  height: 180px;
  border-radius: 18px;
  box-shadow: 0 4px 24px #ffd6e6;
  background: #fff;
}
.soft-link {
  margin-bottom: 8px;
  color: #ff90b3;
  font-size: 0.98rem;
}
.soft-btn {
  background: linear-gradient(90deg, #ffb6e6 0%, #b2f7ef 100%);
  border: none;
  color: #fff;
  font-weight: bold;
  border-radius: 18px;
  box-shadow: 0 2px 8px #ffd6e6;
  padding: 8px 32px;
  font-size: 1.1rem;
  letter-spacing: 1px;
  margin-bottom: 8px;
}
.soft-btn:hover {
  filter: brightness(1.08);
}
.soft-tip {
  color: #b48be6;
  font-size: 0.95rem;
  margin-top: 6px;
}
</style>
